import Vue from 'vue'
import locker from '../../assets/js/lock'

export default (function () {

    /**
     * 加载权限点
     */
    function loadPrivilege(path){
   
        return new Promise((resolve,reject) =>{

            let key = 'privilege:' + path;
            let privilegeData = _g.getCacheData(key); 
            privilegeData = privilegeData ? privilegeData.data : null;
            if(privilegeData){
                resolve(privilegeData);
                return;
            }
            locker.lock(key,()=>{ //加锁
                privilegeData = _g.getCacheData(key); 
                privilegeData = privilegeData ? privilegeData.data : null;
                if(privilegeData){
                    resolve(privilegeData);
                    locker.releaseLock(key);//release lock
                    return;
                }
                _g.putCacheData(key,{requestState:true,reqCount:0});
                console.log(key,'privilege req from server!');
                axios.get("privilege/findButton?url=" + path).then(resp=>{

                    let _data = resp.data.data || [];
                    _g.putCacheData(key, {data : _data , requestState : false});
                    locker.releaseLock(key);//release lock
                    resolve(_data);
                    return;
                });
            });
            
        });

        
    }
    Vue.directive('privilege', {
        
        inserted(el, bind, vNode){
            // console.log(el,bind,vNode);

            if(!bind.value || bind.value.length < 2){
                console.error('directive privilege param error! length >= 2')
                return;
            }
            let path = bind.value[0];


            let funcName = bind.value[1];
        

            loadPrivilege(path).then(privileges=>{

                let filterArr = _.filter(privileges , item=>{
                    return item.name == funcName
                })
                if(!filterArr[0]){//不符合
                    // console.log(funcName , "-> no privilege!!!");
                    Vue.nextTick(()=>{
                        el.remove();
                    });
                }
            });
            // console.log(path,funcName,privileges);

            
        }
    });

})()